package com.springbooti18n.validate.request;

import com.springbooti18n.config.I18nException;
import com.springbooti18n.config.SpringContextUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * xufan
 * 2019/1/16
 */
@ControllerAdvice
public class RequestDataValidate  implements RequestBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        FormValidate formValidate =methodParameter.getParameterAnnotation(FormValidate.class);
        return formValidate !=null;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        return inputMessage;
    }

    @Override
//    @Unc
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter
            , Type targetType, Class<? extends HttpMessageConverter<?>> converterType)
            {
        FormValidate formValidate =parameter.getParameterAnnotation(FormValidate.class);

       Object tar =  SpringContextUtil.getBean(formValidate.beanName());
       boolean isOk = false;
       if(tar instanceof  FormDataHadle){
           isOk = ((FormDataHadle) tar).validate(body);
       }
       if(isOk){
           return body;
       }else{
               throw   I18nException.Buid().setMessageKey("aaaa");

       }

    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }
}
